import cgi
import datetime
import webapp2
import os
import jinja2
import random
import string

from google.appengine.ext import ndb
from google.appengine.api import users
from gaesessions import get_current_session

guestbook_key = ndb.Key('Guestbook', 'default_guestbook')
FICHERO_PALABRAS="words.txt"

class Greeting(ndb.Model):
  author = ndb.UserProperty()
  content = ndb.TextProperty()
  date = ndb.DateTimeProperty(auto_now_add=True)


class MainPage(webapp2.RequestHandler):
	def get(self):
		greetings = ndb.gql('SELECT * '
							'FROM Greeting '
							'WHERE ANCESTOR IS :1 '
							'ORDER BY date DESC LIMIT 10',
							guestbook_key)

		comentario=""
		for greeting in greetings:
			if greeting.author:
				self.response.out.write('<b>%s</b> wrote:' % greeting.author.nickname())
			else:
				self.response.out.write('An anonymous person wrote:')
				comentario+=('<blockquote><p>%s</p></blockquote>' % cgi.escape(greeting.content))

		jinja_environment=jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__),'templates')))
		tpl_vars={"comentario": comentario}
		template=jinja_environment.get_template('Visitas.html')
		self.response.write(template.render(tpl_vars))
		
	def post(self):
		greeting = Greeting(parent=guestbook_key)

		if users.get_current_user():
			greeting.author = users.get_current_user()

		greeting.content = self.request.get('content')
		greeting.put()
		self.redirect('/Visitas')
	  
class Guestbook(webapp2.RequestHandler):
	def post(self):
		greeting = Greeting(parent=guestbook_key)

		if users.get_current_user():
			greeting.author = users.get_current_user()

		greeting.content = self.request.get('content')
		greeting.put()
		self.redirect('/Visitas')
	  

class signin(webapp2.RequestHandler):
	def get(self):
		session=get_current_session()
		count=session.get('count',0)
		firstName=cgi.escape(session.get('firstName',''),quote=True)
		familyName=cgi.escape(session.get('familyName',''),quote=True)
		message=session.get('message')
		session['count']=count+1
		count2=str(count)
		jinja_environment=jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__),'templates')))
		
		tpl_vars={"message": message,"firstName": firstName,"familyName": familyName,"count":count}
		
		template=jinja_environment.get_template('index.html')
		self.response.write(template.render(tpl_vars))
		
	def post(self):
		firstName=self.request.get("firstName")
		familyName=self.request.get("familyName")
		session=get_current_session()
		session['firstName']=firstName
		session['familyName']=familyName
		session['message']=''
		if len(firstName)<2 or len(familyName)<2:
			session['message']="First Name and Family Name are mandatory"
			self.redirect("/")
		self.response.out.write("<script type='text/javascript'>alert('Hola');</script>")
		self.redirect
		
class Ahorcado(webapp2.RequestHandler):
	def get(self):
		session=get_current_session()
		count=session.get('count',1)
		
		letra=session.get('letra','')
		wordlist=session.get('wordlist','')
		session['wordlist']=self.loadWords()
		wordlist=session.get('wordlist')
		
		secretword=session.get('secretword','')
		
		if(secretword==''):
			session['secretword']=self.chooseWord(wordlist)
			session['intentos']=8
			session['lettersGuessed']=[]
			session['auxiliar']=''
		secretword=session.get('secretword')
		
		resultado=session.get('resultado','')
		intentos=session.get('intentos')
		lettersGuessed=session.get('lettersGuessed')
		
		auxiliar=session.get('auxiliar')
		
		session['longitud']=str(len(secretword))
		longitud=session.get('longitud')
		
		session['count']=count+1
		count2=str(count)
		jinja_environment=jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__),'templates')))
		
		
		tpl_vars={"wordlist": wordlist,"letra": letra,"count":count,"secretword":secretword, "resultado":resultado,"intentos":intentos,"longitud":longitud,"lettersGuessed":lettersGuessed,"auxiliar":auxiliar}
		template=jinja_environment.get_template('ahorcado.html')
		self.response.write(template.render(tpl_vars))
		
	def loadWords(self):
		inFile=open(FICHERO_PALABRAS,'r',0)
		linea=inFile.readline()
		lista=string.split(linea)
		return lista
		
	def chooseWord(self,wordlist):
		return random.choice(wordlist)
		
	def isWordGuessed(self,secretWord,lettersGuessed):
		esta=True
		i=0
		while(esta and i<len(secretWord)):
			letraAct=secretWord[i]
			if((letraAct in lettersGuessed)==False):
				esta=False
			else:
				i+=1
		return esta
		
	def getGuessedWord(self,secretWord,lettersGuessed):
		i=0
		palabraNueva=''
		while(i<len(secretWord)):
			letraAct=secretWord[i]
			if((letraAct in lettersGuessed)==False):
				palabraNueva+=' _ '
			else:
				palabraNueva+=letraAct
			i+=1
		return palabraNueva
		
	def getAvailableLetters(self,lettersGuessed):
		letrasDisponibles=''
		alfabeto='abcdefghijklmnopqrstuvwxyz'
		i=0
		while(i<len(alfabeto)):
			if((alfabeto[i] in lettersGuessed)==False):
				letrasDisponibles+=alfabeto[i]
			i+=1
		return letrasDisponibles
	
	def post(self):
		let=self.request.get("letra")
		session=get_current_session()
		wordlist=session.get('wordlist')
		secretWord=session.get('secretword').lower()
		self.response.write(wordlist)
		self.response.write(secretWord)
		self.response.write('hace post')
		
		self.response.write('Bienvenido! :D')
		self.response.write('La palabra tiene '+str(len(secretWord))+' letras')
		
		lettersGuessed=session.get('lettersGuessed')
		
		intentos=session.get('intentos')
		
		auxiliar=session.get('auxiliar')
		
		if(intentos>0 and (self.isWordGuessed(secretWord,lettersGuessed))==False):
			
			self.response.write('Letras disponibles  '+str(self.getAvailableLetters(lettersGuessed)))
			x=let
			x=x.lower()
			if((x in lettersGuessed)==True):
				session['auxiliar']='Ups! Ya lo has intentado con esa letra: '+str(self.getGuessedWord(secretWord,lettersGuessed))
			elif ((x in secretWord)==True):
				lettersGuessed+=[x]
				session['auxiliar']='Acierto! '+str(self.getGuessedWord(secretWord,lettersGuessed))
			else:
				intentos-=1
				lettersGuessed+=[x]
				session['auxiliar']='Ups! Esa letra no esta en la palabra: '+str(self.getGuessedWord(secretWord,lettersGuessed))
			session['intentos']=intentos
					
		
		resultado=session.get('resultado')
		if(not self.isWordGuessed(secretWord,lettersGuessed) and intentos==0):
			session['resultado']='Has perdido. La palabra era: '+str(secretWord)
			resultado=session.get('resultado')
			secretword=session.get('secretword','')
		
		elif(self.isWordGuessed(secretWord,lettersGuessed)):
			session['resultado']='Enhorabuena, has ganado! :D'
			resultado=session.get('resultado')
			
			
		
		self.redirect('/ahorcado')
		


app = webapp2.WSGIApplication([
  ('/Visitas', MainPage),
  ('/', signin),
  ('/sign', Guestbook),
  ('/ahorcado',Ahorcado)
], debug=True)
